/**
 * 处理数字
 * @param num 源数据
 * @param digit 保留小数位数,默认为0
 * @param sign 是否加+号
 * @param allow0 返回值是否可为0,为false时0被替换为'-'
 */
export function solveNumber(
  num: number | string,
  digit: number,
  sign: number | boolean,
  allow0: number | boolean
) {
  if (typeof num !== "number") num = Number(num);
  if (!num && !allow0) return "-";
  let res = num.toLocaleString("zh-CN", {
    minimumFractionDigits: digit || 0,
    maximumFractionDigits: digit || 0,
  });
  // 四舍五入后为0
  if (!allow0 && !Number(res)) return "-";
  if (sign) res = num > 0 ? "+" + res : res;
  return res;
}

/**
 * 处理利率(例: 0.02 -> 2%)
 * @param num 源数据
 * @param digit 小数位数(默认为2)
 */
export function solveRate(num: number | string, digit: number) {
  if (typeof num !== "number") num = Number(num);
  return (num * 100).toFixed(digit || 2) + "%";
}

import { TreeNode, TreeStruct } from "@/interfaces";
/**
 * 拼接树 O(n)
 * @param data 节点数组
 */
export function createTree(data: TreeNode[]): TreeStruct[] {
  const roots = [];
  const nodeMap = new Map();
  for (const node of data) {
    nodeMap.set(node.id, {
      label: node.name,
      value: node.id,
      parentId: node.parentId,
    });
  }
  for (const item of data) {
    const node = nodeMap.get(item.id);
    const parent = nodeMap.get(item.parentId);
    if (item.parentId) {
      if (parent) {
        if (!parent.children) {
          parent.children = [];
        }
        parent.children.push(node);
      } else {
        roots.push(node);
      }
    } else {
      roots.push(node);
    }
  }
  return roots;
}
